<template>
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px">

        <el-form-item label="旧密码:" prop="oldPwd">
            <el-input v-model="form.oldPwd" placeholder="请输入" clearable show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPwd">
            <el-input v-model="form.newPwd" placeholder="请输入" clearable show-password></el-input>
        </el-form-item>
        <el-form-item label="确认新密码:" prop="confirmPwd">
            <el-input v-model="form.confirmPwd" placeholder="请输入" clearable show-password></el-input>
        </el-form-item>
    </el-form>
    <span>
        <el-button @click="resetClick()">重置</el-button>
        <el-button type="primary" :loading="btnLoading" @click="submitClick(formRef)">确 定</el-button>
    </span>
</template>
<script setup lang="ts">
import { updateUserPwd } from '@/api/login';
import { useUserStore } from '@/stores/modules/user';
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
// 表单数据
const form = ref({
    oldPwd: '',
    newPwd: '',
    confirmPwd: ''
})
// 按钮加载状态
const btnLoading = ref(false)
// Form 组件的引用
const formRef = ref<FormInstance>()
// Form 组件验证条件
const formRules = reactive<FormRules>({
    oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPwd: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    confirmPwd: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value: string, callback: Function) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== form.value.newPwd) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
})
const submitClick = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid) => {
        if (valid) {
            const data = {
                oldPwd: form.value.oldPwd,
                newPwd: form.value.confirmPwd
            }
            const res = await updateUserPwd(data);
            if (res.code == 200) {
                btnLoading.value = false;
                ElMessage.success("操作成功！");
                useUserStore().userLogout();
            } else {
                ElMessage.error(res.message);
            }
        } else {
            console.log('error submit!')
            return false
        }
    })
}
const resetClick = () => {
    // 重置表单
    formRef?.value?.resetFields()
}


</script>